# 功能模块：vtk引擎颜色处理和色温逻辑
# 作者：dl
# 描述：vtk的颜色必须做归一化处理

import math

def hex_to_rgba(hex_color):
    hex_color = hex_color.lstrip('#')
    hlen = len(hex_color)
    if hlen == 8:
        r = float(int(hex_color[0:2], 16))/255
        g = float(int(hex_color[2:4], 16))/255
        b = float(int(hex_color[4:6], 16))/255
        a = float(int(hex_color[6:8], 16))/255
        return (r, g, b, a)
    elif hlen == 6:
        r = float(int(hex_color[0:2], 16))/255
        g = float(int(hex_color[2:4], 16))/255
        b = float(int(hex_color[4:6], 16))/255
        return (r, g, b, 1.0)
    else:
        raise ValueError('Invalid hex color: ' + hex_color)


def convert_K_to_RGB(colour_temperature):
    # range check
    if colour_temperature < 1000:
        colour_temperature = 1000
    elif colour_temperature > 40000:
        colour_temperature = 40000

    tmp_internal = colour_temperature / 100.0

    # red
    if tmp_internal <= 66:
        red = 255
    else:
        tmp_red = 329.698727446 * math.pow(tmp_internal - 60, -0.1332047592)
        if tmp_red < 0:
            red = 0
        elif tmp_red > 255:
            red = 255
        else:
            red = tmp_red

    # green
    if tmp_internal <= 66:
        tmp_green = 99.4708025861 * math.log(tmp_internal) - 161.1195681661
        if tmp_green < 0:
            green = 0
        elif tmp_green > 255:
            green = 255
        else:
            green = tmp_green
    else:
        tmp_green = 288.1221695283 * math.pow(tmp_internal - 60, -0.0755148492)
        if tmp_green < 0:
            green = 0
        elif tmp_green > 255:
            green = 255
        else:
            green = tmp_green

    # blue
    if tmp_internal >= 66:
        blue = 255
    elif tmp_internal <= 19:
        blue = 0
    else:
        tmp_blue = 138.5177312231 * \
            math.log(tmp_internal - 10) - 305.0447927307
        if tmp_blue < 0:
            blue = 0
        elif tmp_blue > 255:
            blue = 255
        else:
            blue = tmp_blue

    return red, green, blue

